let currentOutTradeNo = '';
let currentTeamId = '';
let userParticipatedTeamId = null;

// 检查登录状态
function checkLogin() {
    const username = getCookie('username');
    return username !== '';
}

// 获取Cookie
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
    return '';
}

// 设置Cookie
function setCookie(name, value) {
    document.cookie = `${name}=${value};path=/`;
}

// 生成随机订单号
function generateOutTradeNo() {
    return Math.random().toString(36).substr(2, 12);
}

// 格式化当前时间
function formatCurrentTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 初始化轮播图
let currentSlide = 0;
const slides = document.querySelector('.swiper-wrapper');

function nextSlide() {
    currentSlide = (currentSlide + 1) % 4;
    slides.style.transform = `translateX(-${currentSlide * 100}%)`;
}

setInterval(nextSlide, 3000);

// 加载商品数据
async function loadProductData() {
    const username = getCookie('username');
    if (!username) {
        document.getElementById('loginModal').style.display = 'block';
        return;
    }

    try {
        const response = await fetch(`http://localhost:8098/api/v1/gbm/index/query_group_buy_market_config?userId=${username}&source=s01&channel=c01&goodsId=9890001`);
        const data = await response.json();

        if (data.code === '0000') {
            updateUI(data.data);
        }
    } catch (error) {
        console.error('加载数据失败:', error);
    }
}

// 更新UI
function updateUI(data) {
    const { goods, teamList, teamStatistic } = data;

    document.getElementById('deduction').textContent = goods.deductionPrice;
    document.getElementById('buyerCount').textContent = teamStatistic.allTeamUserCount;
    document.getElementById('groupPrice').textContent = goods.payPrice;
    document.getElementById('originalPrice').textContent = goods.originalPrice;

    const teamListContainer = document.getElementById('teamList');
    teamListContainer.innerHTML = '';

    if (teamList && teamList.length > 0) {
        const uniqueTeams = teamList.reduce((acc, team) => {
            if (!acc.some(t => t.teamId === team.teamId)) {
                acc.push(team);
            }
            return acc;
        }, []);

        uniqueTeams.forEach(team => {
            const remainingCount = team.targetCount - team.lockCount;
            const isUserTeam = team.userId === getCookie('username');
            const userId = team.userId;

            if (isUserTeam) {
                userParticipatedTeamId = team.teamId;
            }

            const teamElement = document.createElement('div');
            teamElement.className = `team-item ${isUserTeam ? 'user-team' : ''}`;
            teamElement.innerHTML = `
                        <div class="avatar"></div>
                        <div class="team-info">
                            <div class="team-name"> ${userId}     还差${remainingCount}人成团</div>
                            <div class="countdown" data-teamid="${team.teamId}" data-endtime="${team.validTimeCountdown}"></div>
                        </div>
                        <button class="join-btn"
                                onclick="handleTeamAction('${team.teamId}')"
                                ${isUserTeam ? 'data-user-team="true"' : ''}>
                            ${isUserTeam ? '查看二维码' : '立即抢单'}
                        </button>
                    `;
            teamListContainer.appendChild(teamElement);
        });

        startCountdown();
    } else {
        teamListContainer.innerHTML = '<div style="text-align: center; padding: 20px;">小伙伴，赶紧去开团吧，做村里最靓的仔。</div>';
    }

    // Disable "开团购买" button if user has already participated
    const startGroupButton = document.querySelector('.start-group');
    if (userParticipatedTeamId) {
        startGroupButton.disabled = true;
        startGroupButton.textContent = '已参与拼团';
    } else {
        startGroupButton.disabled = false;
        startGroupButton.textContent = '开团购买';
    }
}

// 处理倒计时
function startCountdown() {
    const countdownElements = document.querySelectorAll('.countdown');
    countdownElements.forEach(element => {
        const teamId = element.dataset.teamid;
        const endTime = element.dataset.endtime;

        if (endTime === '已结束') {
            element.textContent = '已结束';
            element.closest('.team-item').querySelector('.join-btn').disabled = true;
            return;
        }

        const [hours, minutes, seconds] = endTime.split(':').map(Number);
        let totalSeconds = hours * 3600 + minutes * 60 + seconds;

        const updateCountdown = () => {
            if (totalSeconds <= 0) {
                element.textContent = '已结束';
                element.closest('.team-item').querySelector('.join-btn').disabled = true;
                return;
            }

            const h = Math.floor(totalSeconds / 3600);
            const m = Math.floor((totalSeconds % 3600) / 60);
            const s = totalSeconds % 60;
            element.textContent = `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
            totalSeconds--;

            setTimeout(updateCountdown, 1000);
        };

        updateCountdown();
    });
}

// New function to handle team actions
function handleTeamAction(teamId) {
    if (!checkLogin()) {
        document.getElementById('loginModal').style.display = 'block';
        return;
    }

    //joinButton.dataset.userTeam === 'true'
    const joinButton = event.target;
    if (teamId === userParticipatedTeamId) {
        // If it's the user's own team, show QR code directly
        showQRCode(teamId);
    } else {
        handleJoinTeam(teamId);
    }
}

// Updated handleJoinTeam function
async function handleJoinTeam(teamId) {
    currentTeamId = teamId;
    currentOutTradeNo = generateOutTradeNo();

    try {
        const response = await fetch('http://localhost:8098/api/v1/gbm/trade/lock_market_pay_order', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: getCookie('username'),
                teamId: teamId,
                activityId: 100123,
                goodsId: '9890001',
                source: 's01',
                channel: 'c01',
                outTradeNo: currentOutTradeNo,
                notifyUrl: 'http://localhost:8098/api/v1/test/group_buy_notify'
            })
        });

        const data = await response.json();
        if (data.code === '0000') {
            showQRCode(teamId);
        } else {
            alert('下单失败');
        }
    } catch (error) {
        console.error('下单失败:', error);
        alert('下单失败');
    }
}

// New function to show QR code
function showQRCode(teamId) {
    // Here you can add logic to fetch and display the specific QR code for the team
    // For now, we'll just show the generic QR modal
    document.getElementById('qrModal').style.display = 'block';
}

// 处理开团
async function handleStartGroup() {
    if (!checkLogin()) {
        document.getElementById('loginModal').style.display = 'block';
        return;
    }

    if (userParticipatedTeamId) {
        alert('您已参与拼团，不能再开新团');
        return;
    }

    currentTeamId = null;
    currentOutTradeNo = generateOutTradeNo();

    try {
        const response = await fetch('http://localhost:8098/api/v1/gbm/trade/lock_market_pay_order', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: getCookie('username'),
                teamId: null,
                activityId: 100123,
                goodsId: '9890001',
                source: 's01',
                channel: 'c01',
                outTradeNo: currentOutTradeNo,
                notifyUrl: 'http://localhost:8098/api/v1/test/group_buy_notify'
            })
        });

        const data = await response.json();
        if (data.code === '0000') {
            document.getElementById('qrModal').style.display = 'block';
        } else {
            alert('开团失败');
        }
    } catch (error) {
        console.error('开团失败:', error);
        alert('开团失败');
    }
}

// 处理单独购买
function handleBuyAlone() {
    if (!checkLogin()) {
        document.getElementById('loginModal').style.display = 'block';
        return;
    }
    document.getElementById('successModal').style.display = 'block';
}

// 处理支付完成
async function handlePaymentComplete() {
    try {
        const response = await fetch('http://localhost:8098/api/v1/gbm/trade/settlement_market_pay_order', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                source: 's01',
                channel: 'c01',
                userId: getCookie('username'),
                outTradeNo: currentOutTradeNo,
                outTradeTime: formatCurrentTime()
            })
        });

        const data = await response.json();
        if (data.code === '0000') {
            document.getElementById('qrModal').style.display = 'none';
            document.getElementById('successModal').style.display = 'block';
            userParticipatedTeamId = currentTeamId || 'new_team';
            await loadProductData(); // 刷新页面数据
        } else {
            alert('支付失败');
        }
    } catch (error) {
        console.error('支付失败:', error);
        alert('支付失败');
    }
}

// 处理取消支付
function handleCancelPayment() {
    document.getElementById('qrModal').style.display = 'none';
}

// 关闭成功弹窗
function closeSuccessModal() {
    document.getElementById('successModal').style.display = 'none';
}

// 处理登录
async function handleLogin(event) {
    event.preventDefault();
    const username = document.getElementById('username').value;
    setCookie('username', username);
    document.getElementById('loginModal').style.display = 'none';
    await loadProductData();
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', loadProductData);